package com.mcxx.modules.miniSalvation.family.service.write;

import com.mcxx.common.exception.BizException;
import com.mcxx.modules.miniSalvation.family.dao.read.FamilyMemberReadDao;
import com.mcxx.modules.miniSalvation.family.dao.write.FamilySpecialWriteDao;
import com.mcxx.modules.miniSalvation.family.entity.FamilySpecialEntity;
import com.mcxx.modules.miniSalvation.family.service.read.SpecialPeopleReadService;
import com.mcxx.util.Constant;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Slf4j
@Service
@TaTransactional
public class SpecialPeopleWriteService {
    @Resource
    private FamilyMemberReadDao familyMemberReadDao;
    @Resource
    private FamilySpecialWriteDao familySpecialWriteDao;
    @Autowired
    private SpecialPeopleReadService specialPeopleReadService;


    public void addFamilySpecial(FamilySpecialEntity entity) {

        String existedId = specialPeopleReadService.getIdByFamilyIdAndIdcard(entity.getFamilyId(),entity.getIdcard());
        if (StringUtils.isNotEmpty(existedId)) {
            throw new BizException(FailureCode.ERR_10002);
        }

        entity.setId(Constant.getUUID());

        String memberId =familyMemberReadDao.queryMemberIDByidCard(entity.getIdcard());

        if(StringUtils.isNotEmpty(memberId)){

            entity.setMemberId(memberId);
        }

        int rows = familySpecialWriteDao.insertIgnoreNull(entity);
        if (rows == 0) {
            log.error(FailureCode.ERR_9999.getMsg());
            throw new BizException(FailureCode.ERR_9999);
        }
    }


    public void modifyFamilySpecial(FamilySpecialEntity entity) {

        String memberId =familyMemberReadDao.queryMemberIDByidCard(entity.getIdcard());


        if(StringUtils.isNotEmpty(memberId)){
            entity.setMemberId(memberId);
        }


        int rows = familySpecialWriteDao.updateIgnoreNull(entity);

        if (rows == 0) {
            log.error(FailureCode.ERR_9999.getMsg());
            throw new BizException(FailureCode.ERR_9999);
        }
    }


    public void delFamilySpecialById(String id) {
        FamilySpecialEntity entity = new FamilySpecialEntity();
        entity.setId(id);

        int rows = familySpecialWriteDao.delete(entity);


        if (rows == 0) {
            log.error(FailureCode.ERR_9999.getMsg());
            throw new BizException(FailureCode.ERR_9999);
        }
    }


    public void copySpecialPeopleInfo(String familyId) {
        familySpecialWriteDao.copySpecialPeopleInfo(familyId);
    }


    public void deleteSpecialPeopleById(String familyId) {
        familySpecialWriteDao.deleteSpecialPeopleById(familyId);
    }

}
